package edu.ccut.titan.service;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

import edu.ccut.titan.service.impl.TitanManagerService;
import edu.ccut.titan.service.impl.TitanPropertiesService;

/**
 * 利用HostActivator，建立起BundleContext和应用程序之间的交互关系
 * 
 * @see OSGiWebappLoader
 * 
 * @author LeslieGu
 * 
 */
public class HostActivator implements BundleActivator {

	private BundleContext context = null;

	public void start(BundleContext context) throws Exception {
		initalComponentManagerService(context);
		initalTitanPropertiesService(context);
    }

	public void stop(BundleContext arg0) throws Exception {
		this.context = null;
	}

	/**
	 * 获得Osgi容器Bundles的上下文
	 * 
	 * @return
	 */
	public BundleContext getBundleContext() {
		return this.context;
	}

	private void initalComponentManagerService(BundleContext context) {
		ITitanManagerService componentManagerService = ServiceFactory
				.getComponentManagerService(context);

		if (componentManagerService == null) {
			context.registerService(ITitanManagerService.class.getName(),
					new TitanManagerService(), null);
		}
	}

	private void initalTitanPropertiesService(BundleContext context) {
		ITitanPropertiesService titanPropertiesService = ServiceFactory
				.geTitanPropertiesService(context);

		if (titanPropertiesService == null) {
			titanPropertiesService = TitanPropertiesService.getInstance();
			
			context.registerService(ITitanPropertiesService.class.getName(),
					titanPropertiesService, null);
		}
	}
}
